package daoImpl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import utility.Utility;
import dao.OrdersDAO;
import domain.Customer;
import domain.Orders;

public class OrderDaoImpl implements OrdersDAO {

	protected static Logger log = Logger.getLogger(OrderDaoImpl.class);
	
	@Resource(name = "sessionFactory")
	SessionFactory sessionFactory;

	@Override
	public void addOrder(Orders order) {
		log.debug("Adding a new order ...");
		Session session = Utility.getSession(sessionFactory);
		session.save(order);
		log.debug("Added new order successfully!");
	}

	@Override
	public void editOrder(Orders order) {
		log.debug("Editting an exist order ...");
		Session session = Utility.getSession(sessionFactory);
		Orders existOrder = (Orders) session.get(Orders.class, order.getOrderId());
		existOrder.setCustomer(order.getCustomer());
		existOrder.setDateOrder(order.getDateOrder());
		existOrder.setOrderProduct(order.getOrderProduct());
		session.save(existOrder);
		log.debug("Edited an exist order.");
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Orders> getOrder(Customer cust) {
		log.debug("Get orders by customer ...");
		Session session = Utility.getSession(sessionFactory);
		String strQuery = "SELECT ORDER_ID FROM CUSTOMER_ORDER WHERE CUSTOMER_ID = :CUSTOMER_ID";
		Query query = session.createQuery(strQuery);
		query.setParameter("CUSTOMER_ID", cust.getCustomerId());
		List<Integer> listOrderByCust = query.list();
		List<Orders> orderResult = new ArrayList<Orders>();
		if (CollectionUtils.isNotEmpty(listOrderByCust)) {
			for (Integer orderId : listOrderByCust) {
				orderResult.add(getOrderFromOrderId(orderId));
			}
			log.debug("Return a list of order size : " + orderResult.size());
			return orderResult;
		} else {
			return null;
		}
	}

	@Override
	public Orders getOrderFromOrderId(int orderId) {
		log.debug("Getting an order from orderId ...");
		Session session = Utility.getSession(sessionFactory);
		Orders odr = (Orders) session.get(Orders.class, orderId);
		if (null != odr) {
			log.debug("Return an order object!");
			return odr;
		} else {
			log.debug("No record has been found with orderId = " + orderId);
			return null;
		}
	}
}
